<?php
class SiteModel extends Model {
	private $pagesDB;
	
	public function __construct(){
		parent::__construct();
		$this->pagesDB = D('Pages');
	}
	protected $_validate = array(
	    array('title','require','请填写网站名称！'),
		
    );
	protected $_auto = array(
        array('create_time','time',1,'function'),
		array('update_time','time',2,'function'),
		array('update_time','time',1,'function'),
    ); 
	//获取当前站点的管理用户ID，返回ID自然数组
	public function getUser_id($site_id){
		$db = M('Site_user');
		$data = $db -> where(array('site_id' => $site_id)) -> Field('user_id') -> select();
		$ret = array();
		foreach($data as $v){
			$ret[] = $v['user_id'];
		}
		//dump($ret);
		return $ret;
	}
	//检查用户是否有管理权限
	//$uid 用户ID
	//$sid 站点ID
	public function getManage($uid,$sid){
		if(in_array($uid,$this->getUser_id($sid))){
			return true;
		}else{
			return false;
		}
	}
	//当前站点的所有用户
	public function getUser_name($site_id){
		$ids = $this->getUser_id($site_id);
		$map['id'] = array('in', $ids); 
		$data = M('User') -> where($map) ->Field('id,nickname') -> select();
		return $data;
	}
	
	//当前用户的所有站点
	public function getSite_list($user_id){
		$db = M('Site_user');
		$data = $db -> alias('su')->join("left join __SITE__ as s on s.id = su.site_id")-> where(array('user_id' => $user_id)) -> Field('s.*') -> select();
		
		return $data;
	}
	
	//一键复制
	public function copy(){
		if(isset($_POST['id'])){
			$id = intval($_POST['id']);
			if($id == 0) return false;
			$sdata = $this->where(array('id' => $id))->find();
			if(!$sdata){
				$this->error('参数错误!');
			}else{
				unset($sdata['id']);
				$sdata['create_time'] = time();
				$sdata['timeout'] = time() + 365*24*3600;
				$sdata['title'] = date('Y-m-d H:i:s').'-新站点';
				unset($sdata['domain']);
				$insert_id = $this -> data($sdata) -> add();
				
				//复制页面
				$mdb = D('Pages');
				$mdb -> copy($id, $insert_id);
				//设置站点风格
				
				$currentSite = $this->where(array('id' => $insert_id)) -> find();
				
				$saveData['page_header_id'] = $this->pagesDB -> where(array('site_id' =>$insert_id, 'rid' => $currentSite['page_header_id'])) -> getField('id');
				$saveData['page_id'] = $this->pagesDB -> where(array('site_id' =>$insert_id, 'rid' => $currentSite['page_id'])) -> getField('id');
				$saveData['page_footer_id'] = $this->pagesDB -> where(array('site_id' =>$insert_id, 'rid' => $currentSite['page_footer_id'])) -> getField('id');
				
				$this -> where(array('id' => $insert_id)) -> data($saveData) -> save();
				//复制栏目和数据
				$cdb = D('Category');
				
				$map['pid'] = 0;
				$map['site_id'] = $id;
				$cdb -> copy($id, $insert_id, $map, 0);
				$cdb = D('Product_category');
				$cdb -> copy($id, $insert_id, $map, 0);

				//更新该模块中的数据
				D('Modules') -> _flush($insert_id);
				
			}
		}
	}
	
}